package com.hongdee.crm.activity.controller;

import com.hongdee.base.entity.ResultEntity;
import com.hongdee.common.util.DateUtils;
import com.hongdee.common.util.EntityUtils;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.activity.dao.ITCrmCarActivityDao;
import com.hongdee.crm.activity.entity.TCrmCarActivity;
import com.hongdee.crm.activity.service.ITCrmCarActivityService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 名  称:TCrmCarActivityConreoller
 * 类  型: class
 * 描  述:
 * 路  径:com.hongdee.crm.activity.controller;
 * 作  者: 术洪超
 * 日  期:2017-02-24 14:38
 */

@RestController
@RequestMapping("/crm/activity")
public class TCrmCarActivityController {

    @Autowired
    private ITCrmCarActivityService itCrmCarActivityService;

    @Autowired
    private ITCrmCarActivityDao itCrmCarActivityDao;

    /**
     * @param uid   登录用户 ID
     * @param token 登录用户 Token
     * @param start 起始记录
     * @param limit 页面大小
     * @return Map
     * @throws Exception
     * @desc 通过 JDBCDao分页查询
     * @author 术洪超
     */
    @RequestMapping("/page")
    @ResponseBody
    public Map page(@RequestParam(name = "uid", defaultValue = "") String uid,
                    @RequestParam(name = "token", defaultValue = "") String token,
                    @RequestParam(name = "start", defaultValue = "") String start,
                    @RequestParam(name = "limit", defaultValue = "") String limit,
                    @RequestParam(name = "id", defaultValue = "") String id,
                    @RequestParam(name = "status", defaultValue = "") String status,
                    @RequestParam(name = "time", defaultValue = "") String time,
                    @RequestParam(name = "deptId",defaultValue ="")String deptId,
                    @RequestParam(name = "companyId",defaultValue = "")String companyId,
                    @RequestParam(name = "area",defaultValue = "")String area,
                    @RequestParam(name = "brand",defaultValue = "")String brand
    ) throws Exception {

        Map map = itCrmCarActivityService.page(id, status, time, start, limit, uid,deptId,companyId,area,brand);
        map.put("success", true);
        map.put("msg", "分页查询成功！");
        return map;

    }

    /**
     * @param uid   登录用户 ID
     * @param token 登录用户 Token
     * @param id    主键 ID
     * @return ResultEntity
     * @throws Exception
     * @desc 查询详情
     * @author 术洪超
     */
    @RequestMapping("/info")
    @ResponseBody
    public ResultEntity info(@RequestParam(name = "uid", defaultValue = "") String uid,
                             @RequestParam(name = "token", defaultValue = "") String token,
                             @RequestParam(name = "id", defaultValue = "") String id) throws Exception {
        ResultEntity res = new ResultEntity();
        Map map = this.itCrmCarActivityService.info(id);
        res.setData(map);
        res.setSuccess(true);
        res.setMsg("查询详情成功");
        return res;
    }


    /**
     * @param uid   登录用户 ID
     * @param token 登录用户 Token
     * @param id    主键 ID
     * @return ResultEntity
     * @throws Exception
     * @desc 启用活动
     * @author 术洪超
     */
    @RequestMapping("/start")
    @ResponseBody
    public ResultEntity start(@RequestParam(name = "uid", defaultValue = "") String uid,
                              @RequestParam(name = "token", defaultValue = "") String token,
                              @RequestParam(name = "id", defaultValue = "") String id) throws Exception {
        ResultEntity res = new ResultEntity();
        itCrmCarActivityService.update(id, "1");
        res.setSuccess(true);
        res.setMsg("启用成功");
        return res;
    }

    /**
     * @param uid   登录用户 ID
     * @param token 登录用户 Token
     * @param id    主键 ID
     * @return ResultEntity
     * @throws Exception
     * @desc 停用活动
     * @author 术洪超
     */
    @RequestMapping("/stop")
    @ResponseBody
    public ResultEntity stop(@RequestParam(name = "uid", defaultValue = "") String uid,
                             @RequestParam(name = "token", defaultValue = "") String token,
                             @RequestParam(name = "id", defaultValue = "") String id) throws Exception {
        ResultEntity res = new ResultEntity();
        itCrmCarActivityService.update(id, "0");
        res.setSuccess(true);
        res.setMsg("停用成功！");
        return res;
    }

    /**
     * @param data 要保存的活动实体
     * @return ResultEntity
     * @throws Exception
     * @desc 保存添加或者修改的实体内容，通过主键判断
     * @author 术洪超
     */
    @RequestMapping("/save")
    @ResponseBody
    public ResultEntity save(@RequestParam(name = "uid", defaultValue = "") String uid,
                             @RequestParam(name = "token", defaultValue = "") String token,
                             @RequestBody TCrmCarActivity data) throws Exception {

        //判断必填项
        EntityUtils.valid(data);
        String oid = TokenUtil.getCompanyId(uid);
        data.setCompanyId(oid);
        TCrmCarActivity activity = itCrmCarActivityService.saveOrUpdate(data, uid);
        ResultEntity res = new ResultEntity();
        res.setData(activity);
        res.setSuccess(true);
        res.setMsg("保存成功！");
        return res;
    }


    /**
     * @param uid   登录用户 ID
     * @param token 登录用户 Token
     * @param id    主键 ID
     * @return ResultEntity
     * @throws Exception
     * @desc 延长活动时间
     * @author 术洪超
     */
    @RequestMapping("/exTime")
    @ResponseBody
    public ResultEntity exTime(@RequestParam(name = "uid", defaultValue = "") String uid,
                               @RequestParam(name = "token", defaultValue = "") String token,
                               @RequestParam(name = "id", defaultValue = "") String id,
                               @RequestParam(name = "stopDate", defaultValue = "") Long stopDate) throws Exception {
        ResultEntity res = new ResultEntity();
        itCrmCarActivityService.exTime(id, stopDate);
        res.setSuccess(true);
        res.setMsg("延长时间成功！");
        return res;
    }

    /**
     * @return List
     * @throws Exception
     * @desc 品牌下拉菜单
     * @author 术洪超
     */
    @RequestMapping("/combo")
    @ResponseBody
    public List<Map> combo(@RequestParam(name = "uid", defaultValue = "") String uid,
                           @RequestParam(name = "token", defaultValue = "") String token,
                           @RequestParam(name = "inUse", defaultValue = "") String inUse,
                           @RequestParam(name = "companyId", defaultValue = "") String companyId
    ) throws Exception {
        return this.itCrmCarActivityService.combo(uid, inUse,companyId);
    }


    /**
     * @param uid   登录用户 ID
     * @param token 登录用户 Token
     * @param start 起始记录
     * @param limit 页面大小
     * @return Map
     * @throws Exception
     * @desc 通过 JDBCDao分页查询
     * @author 术洪超
     */
    @RequestMapping("/alPage")
    @ResponseBody
    public Map alPage(@RequestParam(name = "uid", defaultValue = "") String uid,
                      @RequestParam(name = "token", defaultValue = "") String token,
                      @RequestParam(name = "start", defaultValue = "") String start,
                      @RequestParam(name = "limit", defaultValue = "") String limit,
                      @RequestParam(name = "usercarId", defaultValue = "") String usercarId

    ) throws Exception {

        Map map = itCrmCarActivityService.alPage(usercarId, start, limit, uid);
        map.put("success", true);
        map.put("msg", "分页查询成功！");
        return map;

    }


    /**
     * @param usercarId  要保存的车辆id的集合
     * @param activityId 活动ID
     * @return ResultEntity
     * @throws Exception
     * @desc 保存添加或者修改的实体内容，通过主键判断
     * @author 术洪超
     */
    @RequestMapping("/alSave")
    @ResponseBody
    public ResultEntity alSave(@RequestParam(name = "uid", defaultValue = "") String uid,
                               @RequestParam(name = "token", defaultValue = "") String token,
                               @RequestParam(name = "activityId", defaultValue = "") String activityId,
                               @RequestBody List<Map<Object, String>> usercarId) throws Exception {

        //判断必填项
        EntityUtils.valid(usercarId);
        System.out.println(activityId);
        itCrmCarActivityService.alSave(usercarId, uid, activityId);
        ResultEntity res = new ResultEntity();
        res.setData(null);
        res.setSuccess(true);
        res.setMsg("保存成功！");
        return res;
    }


    @RequestMapping(value = "/excel/export")
    public void exportExcel(
            @RequestParam(name = "uid", defaultValue = "") String uid,
            @RequestParam(name = "companyId", defaultValue = "") String companyId,
            @RequestParam(name = "id", defaultValue = "") String id,
            @RequestParam(name = "status", defaultValue = "") String status,
            @RequestParam(name = "time", defaultValue = "") String time,
            @RequestParam(name = "start", defaultValue = "") String start,
            @RequestParam(name = "limit", defaultValue = "") String limit,
            @RequestParam(name = "deptId", defaultValue = "") String deptId,
            @RequestParam(name = "area", defaultValue = "") String area,
            @RequestParam(name = "brand", defaultValue = "") String brand,
            HttpServletRequest request,
            HttpServletResponse response
    )
            throws Exception {
        List lists = itCrmCarActivityService.findList( id,  status,  time,  start,  limit,  uid, deptId,
                 companyId, area, brand);

        HSSFWorkbook wb = itCrmCarActivityService.export(lists, uid);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "活动管理";
        response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"),"iso8859-1") +DateUtils.getTimeStr("yyyyMMddHHmmss").toString() + ".xls ");
        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();

    }
    @RequestMapping(value = "/excel/Activity")
    public void activityout(HttpServletRequest request,HttpServletResponse response,
                            @RequestParam(name="uid",defaultValue="")String uid
                                           )throws Exception{
        List lists=itCrmCarActivityService.activity(uid);
        HSSFWorkbook wb=itCrmCarActivityService.exportActivity(lists,uid);
        String fileName="活动详情";
        response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"),"iso8859-1") +DateUtils.getTimeStr("yyyyMMddHHmmss").toString() + ".xls ");
        OutputStream outputStream=response.getOutputStream();
        wb.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
    @RequestMapping(value = "/excel/ActivityCX")
    public ResultEntity activityAll(HttpServletRequest request,HttpServletResponse response,
                            @RequestParam(name="uid",defaultValue="")String uid,
                            @RequestParam(name="start",defaultValue = "0")String start,
                            @RequestParam(name="limit",defaultValue = "50")String limit,
                            @RequestParam(name="name",defaultValue = "")String name,
                            @RequestBody Map data
    )throws Exception{
        List lists=itCrmCarActivityService.ActivePageOut(start,limit,data,uid,name);
        XSSFWorkbook wb=itCrmCarActivityService.ActivityExcel(lists,uid);
        String path = request.getSession().getServletContext().getRealPath(".");
        String fileId = StringUtil.UUID();
        path =   path + File.separator + "upload";

        File filepack = new File(path);
        if(!filepack.exists()){
            filepack.mkdir();
        }
        String filePath =   path + File.separator + fileId + ".xlsx";
        File file = new File(filePath);
        file.createNewFile();
        FileOutputStream fileOut = new FileOutputStream(file);
        wb.write(fileOut);
        fileOut.close();
        ResultEntity res = new ResultEntity();
        res.setSuccess(true);
        res.setData(fileId);
        res.setMsg("文件生成成功！");
        return res;
//
//
//
//        String fileName="活动详情";
//        response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gbk"),"iso8859-1") +DateUtils.getTimeStr("yyyyMMddHHmmss").toString() + ".xls ");
//        OutputStream outputStream=response.getOutputStream();
//        wb.write(outputStream);
//        outputStream.flush();
//        outputStream.close();
    }
     /**
     * 获得正在进行的活动信息
     * @return
     */
    @RequestMapping("/activityIng")
    @ResponseBody
    public ResultEntity getActivity(@RequestParam(name = "uid", defaultValue = "") String uid,
                                    @RequestParam(name = "token", defaultValue = "") String token,
                                    @RequestParam(name = "companyId", defaultValue = "") String companyId,
                                    @RequestParam(name = "vin", defaultValue = "") String vin) throws Exception {
        ResultEntity res=new ResultEntity();
        List<Map<String,Object>> mapList=this.itCrmCarActivityService.getActivityIng(uid,companyId,vin);
        res.setData(mapList);
        res.setSuccess(true);
        return res;
    }
}
